/*
 * @Author: XiaoFeng Chen 
 * @Date: 2018-10-12 10:34:10 
 * @Last Modified by: XiaoFeng Chen
 * @Last Modified time: 2018-10-29 16:53:02
 * 1. 初始化cache  
 * 2. 启动webpack或进行打包
 */
//@ts-check
const cache=require('./cache');
const path = require('path');
const fs = require('fs')
const fser = require('./fser')
const docRender = require('./docer').render
const spawn = require('child_process').spawn;

cache();

// E:\html\leave_work_on_time\exampleServer-demo\README.md E:\html\leave_work_on_time\exampleServer-demo\exampleServer

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

const parDir = resolve('..'); // 父级目录 根目录
const cachePath = resolve('./.cache'); //缓存目录
const curDir = resolve('.') //当前路径

function resolveDaddyPath(dir) {
  return path.join(parDir, dir)
}
//读取配置
const config = require(resolveDaddyPath('./.example.js'))
//配置检查

//当前目录
var cdir = resolve('.').split('\\')
var ignoreDirectoryPattern = new RegExp(`node_modules|${cdir[cdir.length - 1]}|^\\..|dist|package.json|package-lock.json`);

// console.log(ignoreDirectoryPattern)
var timeout ;
fs.watch(parDir, {
  recursive: true
}, (eventType, filename) => {
  if (!ignoreDirectoryPattern.test(filename)) {
    // console.log(`事件类型是: ${eventType}`);
    if (filename) {
        // console.log(`提供的文件名: ${filename}`);
      // } else {
      //   console.log('未提供文件名');
      // }
      var filePath = path.resolve(parDir, filename);
      var npath = path.resolve(cachePath, filename);
      if (eventType === 'rename') {
        if (fs.existsSync(filePath)) {
          // console.log('add')
          fser.copy(filePath, npath, {ignoreDirectoryPattern})
        } else {
          // console.log('remove')
          fser.remove(npath)
        }
      } else {
        fser.copy(filePath, npath, {ignoreDirectoryPattern})
      }
      if(/^docs\\(.)+index\.js$/.test(filename)){
        clearTimeout(timeout)
        timeout=setTimeout(docRender,500)
      }
    }
  }
})

var webpackProcess = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['run', 'dev','--prefix',curDir]);

// 捕获标准输出并将其打印到控制台 
webpackProcess.stdout.on('data', function (data) {
  console.log(`${data}`);
});

// 捕获标准错误输出并将其打印到控制台 
webpackProcess.stderr.on('data', function (data) {
  console.log(`${data}`);
});

// 注册子进程关闭事件 
webpackProcess.on('exit', function (code, signal) {
  console.log('child process eixt ,exit:' + code);
});